package com.uhu.code;

import java.util.*;

/**
 * 438. 找到字符串中所有字母异位词
 * https://leetcode.cn/problems/find-all-anagrams-in-a-string/?envType=study-plan-v2&envId=top-100-liked
 */
public class Solution438 {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        if(s.length() < p.length()) {
            return result;
        }
        p = getSortString(p);
        for(int i = 0; i <= s.length() - p.length(); i++) {
            String sortString = getSortString(s.substring(i, i + p.length()));
            if(sortString.equals(p)){
                result.add(i);
            }
        }
        return result;
    }

    private String getSortString(String s) {
        char [] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}
